const App = getApp();
const util = require('../../utils/util.js');
const api = require('../../utils/api.js');


var interval;


Page({
  data: {
    mobile: '',
    smsCode: '',
    rps_data: '',
    verifyLabel: '获取验证码',
    countNum: null,
    seconds: 60,
    timelength: 60, //倒计时时长（秒）

    btnColor: 'DDD',
    btnDisabled: true,
    verDisabled: true,
    focus:true,
    hold:true
  },


  // 生命周期函数--监听页面卸载
  onUnload: function () {
    clearInterval(interval);//页面卸载时 销毁定时器
  },




  //保存手机号码到页面
  saveMobile: function (e) {

/* 
    console.log("------BBB手机号是--------------")
    console.log(e.detail.value)
    console.log("BBBBBBBBBBBBBBBBB   saveMobile ") */

    this.setData({
      mobile: e.detail.value
    })

  },





  //保存验证码
  saveSmsCode: function (e) {


    if (e.detail.value != '' && e.detail.value.length == 4) {  //长度为4
      //收起键盘
      wx.hideKeyboard()
      this.setData({
        smsCode: e.detail.value,
        //将“确定”按钮变色
        btnColor: 'F3630A',
        //按钮
        btnDisabled: false
      })

    }else{
      this.setData({
        //将“确定”按钮变色
        btnColor: 'DDD',
        //按钮
        btnDisabled: true
      })
    }

  },




  countdown: function (that) {
    console.log('count down');
    var seconds = that.data.seconds;
    console.log(seconds);
    var countNum = that.data.countNum;
    if (seconds <= 1) {
      countNum = null;
      seconds = that.data.timelength;
      that.setData({
        verifyLabel: '获取验证码'
      })
    } else {
      countNum = (--seconds) + 's'
    }
    that.setData({
      seconds: seconds,
      countNum: countNum
    });
  },


  //发送验证码： 
  sendsmscode: function (e) {

/*     console.log(e.currentTarget.dataset)
    console.log(e)

    console.log("------AAA手机号是--------------")
    console.log(this.data.mobile)
    console.log("AAAAAAAAAAAAAAAA  sendsmscode") */


    if (this.validatemobile(this.data.mobile)) {

      //手机号验证通过处理
      const data = {
        mobile: this.data.mobile,

        app_token: App.globalData.app_token,
        security_code: App.globalData.security_code

      }



      this.setData({
        //使可以填写验证码
        verDisabled: false
      })


      var that = this
      if (this.data.countNum == null) {

        api.sendsmscode({
          data,
          success: (res) => {
            console.log("res.data>>>" + res.data);
            var resData = res.data;
            console.log("------------发送验证码接口  返回结果-----");
            console.log(resData);

            that.setData({
              verifyLabel: ''
            })

            //倒计时
            that.setData({
              countNum: that.data.timelength + 's'
            });
            // 启动以1s为步长的倒计时
            interval = setInterval(() => {
              that.countdown(that);
            }, 1000);
            // 停止倒计时
            setTimeout(function () {
              clearInterval(interval);
            }, that.data.timelength * 1000);


            /**
             * 
                      if (this.data.seconds == this.data.timelength) {
                        console.log('post');
                        wx.showToast({
                          title: '发送成功'
                        });
                      }
             */

          },
          fail: (res) => {
            console.log("fail 返回 res.data>>>" + res.data);
          }
        })

      }
    }
  },



  validatemobile: function (mobile) {
    if (mobile.length == 0) {
      App.WxService.showModal({
        title: '友情提示',
        content: '请输入手机号！',
        showCancel: !1,
      })
      return false;
    }
    if (mobile.length != 11) {
      App.WxService.showModal({
        title: '友情提示',
        content: '手机号长度有误！',
        showCancel: !1,
      })
      return false;
    }
    var myreg = /^(((13[0-9]{1})|(147)|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!myreg.test(mobile)) {
      App.WxService.showModal({
        title: '友情提示',
        content: '手机号有误！',
        showCancel: !1,
      })
      return false;
    }
    return true;
  },




  //会员登录接口
  memberLogin: function (e) {

    var isOK = false;

    //验证手机号
    if (this.validatemobile(this.data.mobile)) {

      console.log("---------smsCode-----------")
      console.log(this.data.smsCode)

      if (this.data.smsCode == '') {
        App.WxService.showModal({
          title: '友情提示',
          content: '验证码不能为空！',
          showCancel: !1,
        })
      } else {
        isOK = true;
      }
    }


    if (isOK) {

      const data = {
        member_type_key: 'consumer',
        data_source: 'local_life',
        //    mobile: '15361819668',
        mobile: this.data.mobile,
        device_model: 'Redmi+3',
        sms_code: this.data.smsCode,
        request_info: '00000000-4883-fd33-a0b9-8d657f8a5a89',
        
        app_token: App.globalData.app_token,
        security_code: App.globalData.security_code
      }

      console.log(data)

      api.memberLogin({
        data,
        success: (res) => {
          console.log("....memberLogin>>>" + res.data);
          var resData = res.data;
          console.log(resData);

          if (resData.rsp_code == 'fail') {//登录失败
            console.log(resData.error_code);
            console.log(resData.error_msg);


            //const error = resData.error_msg

            if (resData.error_code == 'check_code_disabled') {
              App.WxService.showModal({
                title: '友情提示',
                content: '输入的验证码错误或失效',
                showCancel: !1,
              })
            }

            return false

          } else if (resData.rsp_code == 'succ') {

            console.log("+++++++++登录成功++++++++++")
            console.log("+++++++++登录成功++++++++++")
            console.log("+++++++++登录成功++++++++++")
            console.log("+++++++++登录成功++++++++++")

            console.log(resData)

            //全局变量
            App.globalData.hasLogin = true,
            App.globalData.memberInfo = resData.data;


            //将  memberInfo 数据存储在本地缓存中
            try {
              console.log("---------- setStorageSync  --------")
              wx.setStorageSync('memberInfo', resData.data)
            } catch (e) {
              console.log(e)
            }

            //调用地理信息
            //this.JingWeiDu()
            //App.getLocation()

            //获取微信用户信息
            App.getUserInfo()

            wx.showLoading({
              title: '登录中...',
            })

            setTimeout(function () {
              wx.hideLoading()

              //登陆成功，跳回上一页 后续再优化
              /* 
              wx.navigateBack({
                delta: 1
              })
              */

              //现在暂时跳回首页
              wx.switchTab({
                url: '/pages/index/index'
              })
            }, 1000)
          }
        },
        fail: (res) => {
          console.log(res.data);
        },
        complete: (res) => {
          console.log("complete 返回 res>>>" + res.data);
          console.log(res.data);
        }
      })

    }
  },

})
